import QtQuick
import FluentUI
import analysis 1.0

FluWindow {
    width: 1152
    height: 540
    fixSize: true
    visible: true
    title: "Sub Client Analysis"
    property string nowQuery: ""

    // 窗体关闭事件重载
    closeListener: function(event){
        if(closeDestory){
            // 关闭所有子窗口
            manager.destroyAllWin()
            // 关闭主窗口
            destoryOnClose()
        }else{
            visible = false
            event.accepted = false
        }
    }

    // 当组建创建完成，初始化数据库
    Component.onCompleted: {
        // 首次读入数据库，初始化左侧列表
        const queryArray = QmlSqlWrapper.getPatientList()
        manager.setPatientListData(queryArray)
    }

    // 创建事件循环开始循环处理任务
    Timer {
        interval: 8000
        running: true
        repeat: true
        onTriggered: {
            TaskWrapper.nextTaskStart()
        }
    }

    // 注册事件处理完成回调
    Connections {
        target: TaskWrapper

        function onTaskRunningDone(filename, errMsg){
            // debug console
            console.log("Done for", filename, "errMsg", errMsg)

            // debug ui
            if(errMsg === ""){
                showSuccess(filename + " deal done", 3000)
            }else{
                showError(filename + " deal error: " + errMsg, 10000)
            }

            // add to ui
            let split_arr = filename.split("-")
            manager.addPatientListItem({patientName: split_arr[1], testId: split_arr[0]})

            // 判断逻辑
            if(nowQuery === (split_arr[1] + "/" + split_arr[0])){
                // 刷新数据库
                const dealArray = QmlSqlWrapper.getDealList(split_arr[1], split_arr[0])
                manager.setPatientTableData(dealArray)
            }
        }
    }

    EMManager{
        id: manager
        width: parent.width
        height: parent.height
        detailSource: "qrc:/ClientAnalysis/UI/EMAnalysisDetail.qml"

        onListItemClick: (r1, r2)=>{
            // 查询数据库并设置给tabledata
            console.log(r1, r2)
            nowQuery = r1 + "/" + r2
            const dealArray = QmlSqlWrapper.getDealList(r1, r2)
            setPatientTableData(dealArray)
        }

        onTableItemClick: (r1, r2, r3)=>{
            // 查询数据json并提交窗体渲染请求
            console.log(r1, r2, r3)

            const s = QmlUiWrapper.getJsonStrFromFile(r1, r2, r3)
            if(s === ""){
                showError("计算文件丢失")
            }else{
                // 创建渲染
                startDetailPage(r1 + "/" + r2 + "/" + r3, s)
            }
        }
    }
}
